package cn.quantgroup.rabbitmq.hello;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * Created by mingzhu on 2016/12/10.
 */
public class Recv {

    //队列名称
    private static final String QUEUE_NAME = "hello";

    public static void main(String[] argv) throws Exception {
        //创建链接工厂,设置用户名密码
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setUsername("admin");
        factory.setPassword("admin");
        Connection connection = factory.newConnection();
        //创建通道
        Channel channel = connection.createChannel();
        //声明队列,发送者和生产者都做了队列声明的操作
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
        //创建消费者,重写消息的处理方法
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
                    throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println(" [x] Received '" + message + "'");
            }
        };
        //消费消息.
        channel.basicConsume(QUEUE_NAME, true, consumer);
    }
}
